package main

import (
	"fmt"
	"sync"
	"time"
)

/*
互斥锁。在golang中没有重入锁的概念。
*/
func main() {

	go func() {
		for i := 0; i < 5; i++ {
			d5_deposit(200, "aaa")
		}
	}()

	go func() {
		for i := 0; i < 5; i++ {
			d5_deposit(200, "bbb")
		}
	}()

	var input string
	fmt.Scanln(&input)
}

// 账号
var (
	// 使用互斥锁
	d5Lock sync.Mutex // guards balance
	//一个只能为1和0的信号量叫做二元信号量(binary semaphore)
	d5Balance int
)

// 存钱
func d5_deposit(amount int, name string) {
	d5Lock.Lock()
	defer d5Lock.Unlock()

	fmt.Println("存钱->begin, name=", name)
	d5Balance += amount
	time.Sleep(1 * time.Second)
	fmt.Println("存钱->end, name=", name)
}

// 查询余额
func d5_balance() int {
	d5Lock.Lock()
	defer d5Lock.Unlock()

	b := d5Balance
	return b
}
